#include <pthread.h>
// #include <stdio.h>
// #include <unistd.h>
// #include <string.h>
#include "apue.h"

pthread_barrier_t pb;
pthread_t t1, t2;

void *th1(void *a)
{
  printf("start t1\n");
  sleep(1);
  // 最后一个完成的线程，返回值应该为-1
  int r = pthread_barrier_wait(&pb);
  printf("th1  r:%d\n", r);
  return NULL;
}

void *th2(void *a)
{
  printf("start t2\n");
  int r = pthread_barrier_wait(&pb);
  printf("th2  r:%d\n", r);
  return NULL;
}

int main()
{
  int r;
  pthread_barrier_init(&pb, NULL, 3);

  pthread_create(&t1, NULL, th1, NULL);
  pthread_create(&t2, NULL, th2, NULL);

  r = pthread_barrier_wait(&pb);
  printf("main r:%d\n", r);

  // 等待子进程结束
  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  return 0;
}